package com.woniu.defecttracking.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.defecttracking.entity.Menus;
import com.woniu.defecttracking.entity.Rule;
import com.woniu.defecttracking.entity.RuleMenus;
import com.woniu.defecttracking.exception.MenusException;
import com.woniu.defecttracking.exception.RuleException;
import com.woniu.defecttracking.mapper.RuleMenusMapper;
import com.woniu.defecttracking.param.AddRuleMenusParam;
import com.woniu.defecttracking.service.MenusService;
import com.woniu.defecttracking.service.RuleMenusService;
import com.woniu.defecttracking.service.RuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tiangle
 * @since 2021-12-31
 */
@Service
public class RuleMenusServiceImpl extends ServiceImpl<RuleMenusMapper, RuleMenus> implements RuleMenusService {

    @Autowired
    private RuleService ruleService;
    @Autowired
    private MenusService menusService;

    /**
    * @作者: 倪西
    * @描述：新增/修改rule和菜单的关联
    * @时间：2022/1/6 15:07
    * @参数：[addRuleMenusParam]
    * @返回：java.lang.Boolean
    **/
    @Override
    public Boolean saveRuleMenus(AddRuleMenusParam addRuleMenusParam) throws RuleException, MenusException {
        Rule rule = ruleService.getById(addRuleMenusParam.getRuleId());
        if (null==rule){
            throw  new RuleException("所选规则状态不存在",2071);
        }
        if (rule.getRuleIsdel()==1){
            throw  new RuleException("所选规则状态不存在",2071);
        }
        remove(new QueryWrapper<RuleMenus>().eq("rule_id",addRuleMenusParam.getRuleId()));

        if (null==addRuleMenusParam.getMenusIds()||addRuleMenusParam.getMenusIds().size()<=0){
            return true;
        }
        int count = menusService.count(new QueryWrapper<Menus>()
                .in("menus_id", addRuleMenusParam.getMenusIds()));
        if (count!=addRuleMenusParam.getMenusIds().size()){
            throw new MenusException("所选菜单项有缺失",811);
        }
        List<RuleMenus> ruleMenusList = new ArrayList<>();
        for (Integer id:addRuleMenusParam.getMenusIds()){
            RuleMenus ruleMenus = new RuleMenus();
            ruleMenus.setRuleId(addRuleMenusParam.getRuleId());
            ruleMenus.setMenusId(id);
            ruleMenusList.add(ruleMenus);
        }
        return saveBatch(ruleMenusList);
    }
}
